import $ from './library/jquery.js';
import cookie from './library/cookie.js';


function changeShopCookie(id, num) {
    let shop = cookie.get('shop'); // 获得购物车信息

    shop = JSON.parse(shop); // 转对象（数组）
    let _index = shop.findIndex(elm => elm.id === id); // 找到已存在数据的索引值
    shop[_index].num = parseInt(num);

    cookie.set('shop', JSON.stringify(shop), 1);
}

let shop = cookie.get('shop');
let goods_num = shop.length;
$('.goods_num').html(`(${goods_num})`);

if (shop) {
    shop = JSON.parse(shop);

    let idList = shop.map(el => el.id).join();

    $.ajax({
        type: "get",
        url: "../../interface/getItems.php",
        data: {
            idList
        },
        dataType: "json"
    }).then(function(res) {

        // console.log(res);

        let tempString = '';

        res.forEach(el => {
            let picture = JSON.parse(el.picture);

            // 让ajax请求数据结果遍历的id与cookie中对应id相同 才可以填写数据
            let current = shop.filter(elm => elm.id === el.id);

            tempString += `
            <div class="par_bot">
            <div>
                <div>
                    <input type="checkbox" class="flag">
                </div>
                <div class="par_smpic">
                   <img src="../${picture[1].src}" alt=""> 
                </div>
            </div>
            <div>
                <div class="par_bot_cen">
                    <div class="par_title">
                        <a href="./goods.html?item=${el.id}">${el.title}</a>
                        <p>赠品|18W快充移动电源 白色</p>
                    </div>
                    <div class="par_price${el.id}">¥<span>${parseFloat(el.price).toFixed(2)}</span></div>
                    <div>
                        <div class="par_num">
                            <div class="iconfont icon-jianhao minute"></div>
                            <input type="number" value="${current[0].num}"  min="1"  max="10" data-id="${el.id}" >
                            <div class="iconfont icon-jiahao add"></div>
                        </div>
                        <div>限购10件</div>
                    </div>
                    <div class="par_sum${el.id}">¥<span  class="pr-sum">${(current[0].num * parseFloat(el.price)).toFixed(2)}</span></div>
                    <div>
                        <div class="removeitem" data-id="${el.id}">删除商品</div>
                        <div>修改商品</div>
                    </div>
                </div>
                <div class="par_bot_zen">
                    <div>
                        <a href="#">
                            <div>赠品</div>
                            <img src="../img/shopping.png" alt="">
                            <p>18W快充移动电源 白色</p>
                        </a>
                    </div>
                    <div>¥0</div>
                    <div>x1</div>
                </div>
            </div></div>`;
        });

        //删除商品
        $('.particulars').append(tempString).find('.removeitem').on('click', function() {
            let res = shop.filter(el => el.id !== $(this).attr('data-id'));
            cookie.set('shop', JSON.stringify(res), 1);
            $('.goods_num').html(`(${goods_num})`);
            location.reload();
        });

        //改变数量 改变cookie中的值,同时改变小计
        $('input').on('change', function() {
            let num = $(this).val();
            let id = $(this).attr('data-id');
            let price = $(`.par_price${id}>span`).html();
            changeShopCookie(id, num);
            $(`.par_sum${id}>span`).html((price * num).toFixed(2));
        });

        // 总价
        let sum = 0;
        for (let i = 0; i < goods_num; i++) {
            sum += parseInt($('.particulars .pr-sum').eq(i).html());
        }
        $('.goods_sum').html(sum.toFixed(2));
        // 结算
        $('.settlement').html(goods_num);


    }).catch(function(xhr) {
        console.log(xhr.status);
    });
}


$('.particulars').on('click', '.minute', function(ev) {
    let input = $(ev.target).siblings('input');
    input.val((index, value) => --value);
    input.val() < 1 && input.val(1);
    input.trigger('change');
})
$('.particulars').on('click', '.add', function(ev) {
    let input = $(ev.target).siblings('input');
    input.val((index, value) => ++value);
    input.val() > 10 && input.val(10);
    input.trigger('change');
})